/*
 * MainUI.java
 *
 * Copyright 2006, Dag Rune Sneeggen
 * 
 * This file is part of Vispace.
 * 
 * Vispace is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * Vispace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Vispace; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

package jvisualfs;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
//import jvisualfs.ImagePanel;

/**
 *
 * @author  dud
 */
public class MainUI extends javax.swing.JFrame {
    
    /** Creates new form MainUI */
    public MainUI() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        VisPanel = new jvisualfs.ImagePanel();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Vispace"));
        VisPanel.setBackground(new java.awt.Color(255, 255, 255));
        VisPanel.setName("VisPanel");
        VisPanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                VisPanelMouseMoved(evt);
            }
        });
        VisPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                VisPanelMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout VisPanelLayout = new org.jdesktop.layout.GroupLayout(VisPanel);
        VisPanel.setLayout(VisPanelLayout);
        VisPanelLayout.setHorizontalGroup(
            VisPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 418, Short.MAX_VALUE)
        );
        VisPanelLayout.setVerticalGroup(
            VisPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 440, Short.MAX_VALUE)
        );

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(VisPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(VisPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Information"));
        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 177, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 441, Short.MAX_VALUE)
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 35, Short.MAX_VALUE)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void VisPanelMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_VisPanelMouseMoved
// TODO add your handling code here:
        //System.out.println("MOUSEMOVED:" + evt.getX() + ":::" + evt.getY());
        if (VisFX.isCoord(evt.getX(), evt.getY())) {
            //System.out.println("HILIGHT!!!");
            VisFX.setHiLightByCoord(evt.getX(), evt.getY());
        } else {
            VisFX.removeAllHiLight();
        }
        VisFX.redraw();        
    }//GEN-LAST:event_VisPanelMouseMoved

    private void VisPanelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_VisPanelMouseClicked
// TODO add your handling code here:

        /*long size = DirPack.get("/storage/unus/Java_apps/math/nbproject/private").getLength();
        System.out.println("PRIV..." + size);
        long size2 = DirPack.get("/storage/unus/Java_apps/math/nbproject").getLength();
        System.out.println("NB..." + size2);*/
        /*
        int j = 0;                 
        while (j < DirPack.size()) {
            //System.out.println("SISSS " + this.dirs.size() + "IIIiii " + i);
            DirStruct tmp = (DirStruct) DirPack.getNum(j);
            System.out.println("POS: " +  j + " NAME: " + tmp.getName() + " SIZE: " + tmp.getLength());
            j++;
        }*/
    }//GEN-LAST:event_VisPanelMouseClicked
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainUI().setVisible(true);
            }
        });
        /*Vector FSTest = new Vector();
        FSTest.add(new Vector());
        FSTest[0].add(new DirStruct(new File("/home/dud/jsp-api.jar")));
        FSTest[0].add(new DirStruct(new File("/home/dud/jsp-api.jar")));
        FSTest.add(new DirStruct(new File("/home/dud/jsp-api.jar")));*/
        //GenFX.setImage(VisPanel);
        DirStruct DSTest = new DirStruct(new File("/storage/unus/photos"));
        //DirStruct DSTest = new DirStruct(new File("/storage/unus/kake/dh/"));
        /*int[] co = { 1, 3 , 5, 6};
        DSTest.setCoord(co);
        System.out.println("L: " + DSTest.getLength() + " N: " + DSTest.getName());
        for (int coord : DSTest.getCoord()) {
            System.out.println("CO: " + coord);
        }*/
        System.out.println("HMM??");
        DirPack = new DirCollection();
        GenFS.traverse(DirPack.add(DSTest), DSTest, DirPack, true);
        
        //System.out.println("MIP:" + MainUI.VisPanel.getName());
        VisFX = new GenFX(VisPanel);
        DirPack.sort();
        int len = 10;
        //System.out.println("SIZE " + DirPack.size());
        if (DirPack.size() < len) {
            //System.out.println("1");
            len = DirPack.size(); 
        }
        for (int j = 0; j < len; j++) {
            DirStruct tmp = (DirStruct) DirPack.getNum(j);
            if (tmp.hasParent("/storage/unus/photos")) {
                //System.out.println("POS: " +  j + " NAME: " + tmp.getName() + " SIZE: " + tmp.getLength());
                VisFX.addComp(tmp);
            }
        }
        VisFX.redraw();
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public static jvisualfs.ImagePanel VisPanel;
    public static javax.swing.JPanel jPanel1;
    public static javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
    public static DirCollection DirPack;
    public static GenFX VisFX;
}
class GenFX {
    // Field members...
    private ImagePanel ip;
    private BufferedImage img;
    private Graphics2D g2d;
    private DirCollection dirs;
    private DirStruct dir;
    private int height;
    private int imgWidth;
    private int imgHeight;
    
    // Constructor
    public GenFX(ImagePanel ip) {
        this.ip = ip;
        this.imgWidth = 400;
        this.imgHeight = 420;
        this.img = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        this.g2d = img.createGraphics();
        this.dirs = new DirCollection();
    }
    public void addComp (DirStruct dir) {
        dirs.add(dir);
    }
    public DirStruct getComp(int k) {
        DirStruct tmp = (DirStruct) this.dirs.getNum(k);
        return (DirStruct) tmp;            
    }
    public boolean isCoord(int x, int y) {        
        //System.out.println("X " + x + " Y " + y);
        for (int j = 0; j < this.dirs.size(); j++) {
            DirStruct tmp = (DirStruct) this.dirs.getNum(j);
            int[] co = tmp.getCoord();
            //System.out.println(" X1 " + co[0] + " X2 " + co[1] + " Y1 " + co[2] + " Y2 " + co[3]);
            if ((x > co[0] && x < co[1]) && (y > co[2] && y < co[3])) {
                //System.out.println("YES::: X1 " + co[0] + " X2 " + co[1] + " Y1 " + co[2] + " Y2 " + co[3]);
                return true;
            }
        }
        return false;
    }
    public void removeAllHiLight() {
        for (int l = 0; l < this.dirs.size(); l++) {
            DirStruct tmp = (DirStruct) this.dirs.getNum(l);
            tmp.setHilight(false);
        }
    }
    public void setHiLightByCoord(int x, int y) {
        for (int k = 0; k < this.dirs.size(); k++) {
            DirStruct tmp = (DirStruct) this.dirs.getNum(k);
            int[] co = tmp.getCoord();
            if ((x > co[0] && x < co[1]) && (y > co[2] && y < co[3])) {
                //System.out.println("HIGHLIGHT??????????" + tmp.getName());
                tmp.setHilight(true);
            }
        }
    }
    public void setImage(ImagePanel ip) {
        this.ip = ip;
    }
    public void redraw() {
        //System.out.println("WH:" + ip.getWidth() + " - " + ip.getHeight());
        g2d.setColor(Color.white);
        g2d.fillRect(0, 0, imgWidth, imgHeight);

        //int[] cols = { 480225, 435654 , 401236, 369878, 300654, 208765, 150879, 135888, 120245, 90000, 70342, 50987, 22222, 15000};
        float magicInt = (imgHeight / (float) dirs.getNum(0).getLength());
        for (int j = 0; j < dirs.size(); j++) {
            int h = Math.round(dirs.getNum(j).getLength() * magicInt);
            float hue = ((0.071f * imgHeight)/h);
            float br = 0.8f;
            if (dirs.getNum(j).isHilight()) {
                br = 1.0f;
            }
            g2d.setColor(Color.getHSBColor(hue,1,br));
            g2d.fill3DRect((10+(30*j)), (imgHeight-h), 20, h, true);
            int[] coord = {(10+(30*j)), (10+(30*j)+20), (imgHeight-h), (imgHeight)};
            dirs.getNum(j).setCoord(coord);
        }
        ip.setImage(img);
        ip.repaint();
    }
}
class GenFS {
    public static void traverse(DirStruct dir, DirStruct parent, DirCollection col, boolean isRoot) {
        System.out.println("Starting traverse..." + dir.getName() /*+ " PARENT: " + parent.getName()*/);
        if (isRoot) {
            //col.get(dir.getName()).setParent("ROOT");
        } else {
            col.get(dir.getName()).setParent(parent);
        }        
        FileFilter SymlinksFilter = new FileFilter() {
            public boolean accept(File file) {
                try {
                    return file.getCanonicalPath().equals(file.getAbsolutePath());
                } catch (IOException e) {
                    return false;
                }
            }
        };
        File[] list = dir.getFp().listFiles(SymlinksFilter);
        for (File tmpdir : list) {
            //System.out.println("NAME: " + tmpdir.getAbsolutePath() /*+ tmpdir.isDirectory() + tmpdir.isFile()*/);
            if (tmpdir.isDirectory()) {
                //System.out.println("NAME: " + tmpdir.getAbsolutePath() + " DIR!!!");
                traverse(col.add(new DirStruct(tmpdir)), dir, col, false);                
            } else if (tmpdir.isFile()) {
                //System.out.println("NAME: " + tmpdir.getAbsolutePath() + " FILE: " + tmpdir.length());
                long newlength = col.get(dir.getName()).getLength() + tmpdir.length();
                col.get(dir.getName()).setLength(newlength);
            }            
        }
        System.out.println("Done traversing!");
        if (!isRoot) {
            //System.out.println(col.get(dir.getParent().getName()).getLength() + " -_- " + col.get(dir.getName()).getLength());
            long travlength = col.get(dir.getParent().getName()).getLength() + col.get(dir.getName()).getLength();        
            //System.out.println("TRAVL: " + travlength);
            col.get(dir.getParent().getName()).setLength(travlength);
            //System.out.println("DLEN: " + col.get(dir.getParent().getName()).getLength());
        }
    }
}
class DirCollection {
    // Fields declarations
    private Vector dirs;
    
    
    // Constructor
    public DirCollection() {
        this.dirs = new Vector();
    }
    
    
    // Methods
    public DirStruct add(DirStruct dir) {
        dirs.add(dir);
        //return (DirStruct) dirs.get(dirs.size());
        return dir;
    }
    public void sort() {        
        Vector SortedDirs = new Vector(this.dirs.size());
        SortedDirs.add(0, dirs.get(0));
        for (int l = 1; l < dirs.size(); l++) {
            boolean isInserted = false;
            DirStruct lDir = (DirStruct) dirs.get(l);
            for (int m = 0; m < SortedDirs.size(); m++) {
                DirStruct mDir = (DirStruct) SortedDirs.get(m);
                if (lDir.getLength() > mDir.getLength()) {
                    SortedDirs.insertElementAt(lDir, m);
                    isInserted = true;
                    break;
                }
            }
            if (!isInserted) {
                SortedDirs.add(lDir);
            }
        }
        this.dirs = SortedDirs;
    }
    public DirStruct get(String name) {
        int i = 0;
        while (i < this.dirs.size()) {
            //System.out.println("SISSS " + this.dirs.size() + "IIIiii " + i);
            DirStruct tmp = (DirStruct) this.dirs.get(i);
            //System.out.println(tmp.getName()+ " 0.0.0.0 " + name);
            if (tmp.getName().equals(name)) {
                return (DirStruct) tmp;
            }
            i++;
        }
         return null;
    }
    
    public int size() {
        return dirs.size();
    }
    public DirStruct getNum(int k) {
        DirStruct tmp = (DirStruct) this.dirs.get(k);
        return (DirStruct) tmp;            
    }
}
